package service;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import daoImp.UserDaoImp;
import model.MessageException;
import model.User;

public class RegisterServlet extends HttpServlet {

	private static final long serialVersionUID = -7585221032171804828L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		this.doPost(request, response);
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		try {
			String uname = request.getParameter("uname");
			String upassword = request.getParameter("upassword");
			String conPwd = request.getParameter("conPwd");
			if (!upassword.equals(conPwd)) {
				//throw new MessageException("两次密码不一致");
				request.setAttribute("msg", "两次密码不一致");
				request.getRequestDispatcher("User_register.jsp").forward(request,
						response);
			}
			User user = new User();
			user.setUname(uname);
			user.setUpassword(upassword);
			UserDao dao = new UserDaoImp();
			if (!dao.isExist(uname)) {
				dao.addUser(user);
				System.out.println(user.getUname() + " register");
				request.setAttribute("msg", "用户：" + uname + ",注册成功");
				request.getRequestDispatcher("Login.jsp").forward(request,
						response);
				// response.sendRedirect("ShowAllUserServlet");
			}
			else {
				System.out.println(user.getUname() + " fail register");
				request.setAttribute("msg", "用户名"+uname+"已存在");
				request.getRequestDispatcher("User_register.jsp").forward(request,
						response);
			}
		} catch (Exception e) {
			request.setAttribute("exception", e);
			request.setAttribute("url", request.getContextPath()
					+ "/User_register.jsp");
			request.setAttribute("urlInfo", "返回注册页面");
			//response.sendRedirect("User_register.jsp");
		}
		out.flush();
		out.close();
	}

}
